package com.jiuqian.demo.service.weixin.impl;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.jiuqian.demo.service.weixin.WxChantService;
import com.jiuqian.demo.utils.weixin.MessageUtil;
import com.jiuqian.demo.utils.weixin.TextMessage;
import com.jiuqian.demo.web.controller.WeiXinController;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;

/**
 *
 * @Date 2017年8月18日 上午9:56:36
 * @Version 1.0
 *
 */
@Service
public class WxChantServiceImpl extends HttpServlet implements WxChantService {

	private static final Logger LOGGER = LoggerFactory.getLogger(WxChantServiceImpl.class);

	private static final long serialVersionUID = 7943680635876311715L;

	protected WxMpInMemoryConfigStorage config;
	protected WxMpService wxMpService;
	protected WxMpMessageRouter wxMpMessageRouter;

	public void init() throws ServletException {
		super.init();
		config = new WxMpInMemoryConfigStorage();
		config.setAppId("wx5de8e8eaef66636b"); // 设置微信公众号的appid
		config.setSecret("6c83ebb41b2636d6b15c7691a858f696"); // 设置微信公众号的app
																// corpSecret
		config.setToken("hanqinlin"); // 设置微信公众号的token
		// config.setAesKey(""); // 设置微信公众号的EncodingAESKey

		wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(config);

	}

	@Override
	public String security(HttpServletRequest request, Integer microId, String signature, String nonce,
			String timestamp, String echostr, String encryptType, String msgSignature)
			throws IOException, ServletException {
		init();
		System.out.println("token : " + timestamp);
		System.out.println("nonce : " + nonce);
		System.out.println("echostr : " + echostr);
		System.out.println("signature : " + signature);

		if (StringUtils.isNotBlank(echostr)) {
			System.out.println("echostr");
			return echostr;
		}
		if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
			// 消息签名不正确，说明不是公众平台发过来的消息
			return "非法请求";
		}
		if (StringUtils.isBlank(encryptType)) {
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
			return "SUCCESS";
		}
		return "";

	}

	@Override
	public String weixinPost(HttpServletRequest request) {
		String respMessage = null;
		try {
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.xmlToMap(request);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			// 消息内容
			String content = requestMap.get("Content");

			LOGGER.info(
					"FromUserName is:" + fromUserName + ", ToUserName is:" + toUserName + ", MsgType is:" + msgType);

			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				// 这里根据关键字执行相应的逻辑，只有你想不到的，没有做不到的
				if (content.equals("xxx")) {

				}

				// 自动回复
				TextMessage text = new TextMessage();
				text.setContent("the text is" + content);
				text.setToUserName(fromUserName);
				text.setFromUserName(toUserName);
				text.setCreateTime(new Date().getTime() + "");
				text.setMsgType(msgType);

				respMessage = MessageUtil.textMessageToXml(text);

			} /*
				 * else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT))
				 * {// 事件推送 String eventType = requestMap.get("Event");// 事件类型
				 * 
				 * if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {//
				 * 订阅 respContent = "欢迎关注xxx公众号！"; return
				 * MessageResponse.getTextMessage(fromUserName , toUserName ,
				 * respContent); } else if
				 * (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {//
				 * 自定义菜单点击事件 String eventKey = requestMap.get("EventKey");//
				 * 事件KEY值，与创建自定义菜单时指定的KEY值对应 logger.info("eventKey is:"
				 * +eventKey); return xxx; } } //开启微信声音识别测试 2015-3-30 else
				 * if(msgType.equals("voice")) { String recvMessage =
				 * requestMap.get("Recognition"); //respContent =
				 * "收到的语音解析结果："+recvMessage; if(recvMessage!=null){ respContent
				 * = TulingApiProcess.getTulingResult(recvMessage); }else{
				 * respContent = "您说的太模糊了，能不能重新说下呢？"; } return
				 * MessageResponse.getTextMessage(fromUserName , toUserName ,
				 * respContent); } //拍照功能 else
				 * if(msgType.equals("pic_sysphoto")) {
				 * 
				 * } else { return MessageResponse.getTextMessage(fromUserName ,
				 * toUserName , "返回为空"); }
				 */
			// 事件推送
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				String eventType = requestMap.get("Event");// 事件类型
				// 订阅
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {

					TextMessage text = new TextMessage();
					text.setContent("欢迎关注，xxx");
					text.setToUserName(fromUserName);
					text.setFromUserName(toUserName);
					text.setCreateTime(new Date().getTime() + "");
					text.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);

					respMessage = MessageUtil.textMessageToXml(text);
				}
				// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {// 取消订阅

				}
				// 自定义菜单点击事件
				else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
					String eventKey = requestMap.get("EventKey");// 事件KEY值，与创建自定义菜单时指定的KEY值对应
					if (eventKey.equals("customer_telephone")) {
						TextMessage text = new TextMessage();
						text.setContent("0755-86671980");
						text.setToUserName(fromUserName);
						text.setFromUserName(toUserName);
						text.setCreateTime(new Date().getTime() + "");
						text.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
						respMessage = MessageUtil.textMessageToXml(text);
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error("error......");
		}
		return respMessage;
	}

}
